package com.bwt.top.bwt_ad_flutter.view.factory;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bwt.top.bwt_ad_flutter.config.BwtAdParamConfig;
import com.bwt.top.bwt_ad_flutter.model.AdParams;
import com.bwt.top.bwt_ad_flutter.view.widget.BwtNativeExpressAdWidget;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;

public class BwtNativeExpressAdFactory extends PlatformViewFactory {
    private final Map<String, BwtNativeExpressAdWidget> adMap = new HashMap<>();

    public BwtNativeExpressAdFactory() {
        super(StandardMessageCodec.INSTANCE);
    }

    @NonNull
    @Override
    public PlatformView create(Context context, int viewId, @Nullable Object args) {
        AdParams adParams = new AdParams();
        if (args != null) {
            try {
                Map<String, Object> params = (Map<String, Object>) args;

                adParams.setAdId(String.valueOf(params.get(BwtAdParamConfig.KEY_AD_ID)));
                adParams.setAdLoaderId(String.valueOf(params.get(BwtAdParamConfig.KEY_AD_LOADER_ID)));
                adParams.setAdWidth((Double) params.get(BwtAdParamConfig.KEY_AD_WIDTH));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        BwtNativeExpressAdWidget platformView = adMap.get(adParams.getAdId());
        if (platformView != null) return platformView;

        BwtNativeExpressAdWidget adWidget = new BwtNativeExpressAdWidget(context, adParams);
        adMap.put(adParams.getAdId(), adWidget);
        return adWidget;
    }

    /**
     * 全部释放
     */
    public void release() {
        for (BwtNativeExpressAdWidget platformView : adMap.values()) {
            if (platformView != null) platformView.release();
        }
        adMap.clear();
    }

    /**
     * 根据 adId 释放
     */
    public void release(String adId) {
        BwtNativeExpressAdWidget platformView = adMap.get(adId);

        if (platformView != null) {
            platformView.release();
            adMap.remove(adId);
        }
    }
}
